package org.goyo.main.web.controller.base;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.goyo.common.baseBean.AjaxResult;
import org.goyo.common.baseBean.Constants;
import org.goyo.common.excel.ExcelUtil;
import org.goyo.common.exception.DBException;
import org.goyo.common.exception.ServiceException;
import org.goyo.common.utils.JSONUtil;
import org.goyo.common.utils.Pager;
import org.goyo.common.utils.ToolUtils;
import org.goyo.main.domain.entity.BaseObject;
import org.goyo.main.domain.entity.base.Material;
import org.goyo.main.domain.entity.system.SysUser;
import org.goyo.main.domain.excelBean.MaterialExcel;
import org.goyo.main.services.base.IMaterialService;
import org.goyo.main.services.log.MethodLog;
import org.goyo.main.web.controller.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 商品
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/material")
public class MaterialController extends BaseController {
  protected Logger logger = LoggerFactory.getLogger(this.getClass());

  @Resource
  private IMaterialService materialService;

  /**
   * 列表界面
   * 
   * @author chenchuan 2014年11月9日
   */
  @RequestMapping("/toMaterialList")
  public String toMaterialList() {
    logger.info("----------------------");
    return "/base/MaterialList";
  }
  
  @RequestMapping("/toExcelImport")
  public String toExcelImport() {
    return "/base/improtExcel";
  }
  
  @MethodLog("导入商品excle")
  @RequestMapping("/importMterialExcel")
  @ResponseBody
  public AjaxResult importMterialExcel(HttpServletRequest request,HttpServletResponse response){
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile files = multipartRequest.getFile("file");
    if(files.getSize()!=0){
        try {
            Map<Object,Object> result = ExcelUtil.ExcelImportToObjec(MaterialExcel.class, ExcelUtil.getBytes(files.getInputStream()),false);
            if(null!=result){
                if(result.get(true)!=null){
                    List<MaterialExcel> list = (List<MaterialExcel>) result.get(true);
                    if(null!=list&&null!=list.get(0)){
                      materialService.saveOrUpdateMaterialList(list);
                    }else{
                        return  AjaxResult.resultFail("数据不完整，请检查后导入！",null);
                    }
                    int validData = list.size();
                    return AjaxResult.resultSuccess("导入成功，共保存"+validData+"条数据！",null);
                }else if(result.get(false)!=null){
                    return AjaxResult.resultFail((String)result.get(false),null);
                }else{
                    return AjaxResult.resultFail("发生错误，导入失败！",null);
                }
            }else{
                return AjaxResult.resultFail("可转换内容为空，导入失败！",null);
            }
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
            return AjaxResult.resultFail("发生错误，导入失败！",null);
        }
    }else{
        return AjaxResult.resultFail("文件大小为零，导入失败！",null);
    }
  }
  

  @RequestMapping("/exportExcel")
  public void exportExcel(HttpServletRequest request,HttpServletResponse response,Model model){
    try {
      String rigidCondition = request.getParameter("rigidCondition");
      String where = request.getParameter("where");
      //左边树的id
      if(!StringUtils.isEmpty(rigidCondition)){
        if(where != null && !"".equals(where)){
          where = where + " and "+rigidCondition+" ";
        }else{
            where = rigidCondition;
        }
      }
      List<MaterialExcel> list = materialService.queryExportDate(where);
      this.execlExport(list, ExcelUtil.XLSX, "商品", response);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      logger.error(e.getMessage(), e); 
    }
  /*    String[] titles = {"车牌号","主驾","事故驾驶员","事故驾驶员身份","事故时间",
              "事故地点","索赔金额","修理费欠费","赔付率","事故罚款",
              "碰撞性质","事故责任","处理程序","处理机关","保险公司",
              "结案情况","人伤处理情况","事故登记人","保司赔付金额","结案日期"};
      String[] data = {"车牌号","主驾","事故驾驶员","事故驾驶员身份","事故时间",
          "事故地点","索赔金额","修理费欠费","赔付率","事故罚款",
          "碰撞性质","事故责任","处理程序","处理机关","保险公司",
          "结案情况","人伤处理情况","事故登记人","保司赔付金额","结案日期"};
      List list = new ArrayList();
      list.add(new Object[]{data});
      this.UserDefinedExeclExport(list,
              Arrays.asList(titles), ExcelUtil.XLSX, "车辆事故", response);*/
      
     /*   response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        String fileName = System.currentTimeMillis() + ".xlsx";
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        Map<String, Object> mapMessage = new HashMap<String, Object>();

        try { //从数据库中得到结果
            OutputStream out = response.getOutputStream();
            SXSSFWorkbook wb = new SXSSFWorkbook(-1);
            // turn off auto-flushing and accumulate all rows in memory
            wb.setCompressTempFiles(true); //使用gzip压缩,减小空间占用
            Sheet sh = wb.createSheet("下载日志");
            //设置每一列的宽度,注意 要乘以256,因为1代表excel中一个字符的1/256的宽度
            sh.setColumnWidth(0, 40 * 256);
            sh.setColumnWidth(1, 40 * 256);
            sh.setColumnWidth(2, 22 * 256);
            Row rowHeader = sh.createRow(0);
            Cell cellHeader = rowHeader.createCell(0);
            cellHeader.setCellValue("id");
            cellHeader = rowHeader.createCell(1);
            cellHeader.setCellValue("name");
            cellHeader = rowHeader.createCell(2);
            cellHeader.setCellValue("create_time");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            for(int rownum = 1; rownum < list.size() + 1; rownum++) {
                Row row = sh.createRow(rownum);
                Cell cell = row.createCell(0);
                cell.setCellValue(list.get(rownum - 1).getId());
                cell = row.createCell(1);
                cell.setCellValue(list.get(rownum - 1).getName());
                cell = row.createCell(2);
                cell.setCellValue(simpleDateFormat.format(list.get(rownum - 1).getCreateTime()));

                // manually control how rows are flushed to disk
                if(rownum % 100 == 0) {  // ((SXSSFSheet)sh).flushRows(100); // retain 100 last rows and flush all others
                    ((SXSSFSheet) sh).flushRows();
                    //is a shortcut for ((SXSSFSheet)sh).flushRows(0),
                    // this method flushes all rows
                }
            }

            wb.write(out);
            out.close();
            // dispose of temporary files backing this workbook on disk
            wb.dispose();
        } catch(Exception e) {
            e.printStackTrace();
        }*/
  }

  /**
   * 保存或者更新
   * 
   * @author chenchuan 2014年11月9日
   */
  @MethodLog("保存或者更新商品信息")
  @RequestMapping("/saveOrUpdateMaterial")
  @ResponseBody
  public AjaxResult saveOrUpdateMaterial(HttpServletRequest request) {
    AjaxResult result = null;
    try {
      String material = request.getParameter("material");
      Material materialBean = JSONUtil.json2Obj(material, Material.class);
      BaseObject obj = materialService.saveOrUpdateInfo(materialBean);
      result = AjaxResult.resultSuccess("保存成功", obj);
    } catch (DBException | ServiceException e) {
      result = AjaxResult.resultFail("保存失败", null);
      logger.error(e.getMessage(), e);
    }
    return result;
  }

  /**
   * 删除
   * 
   * @author chenchuan 2014年11月9日
   */
  @MethodLog("删除商品信息")
  @RequestMapping("/delMaterial")
  @ResponseBody
  public AjaxResult delMaterial(HttpServletRequest request) {
    AjaxResult result = null;
    try {
      String rows = request.getParameter("rows");
      JSONArray jsonarray = JSONArray.fromObject(rows);
      List<Material> list = (List<Material>) JSONArray.toCollection(jsonarray, Material.class);
      materialService.delByUuids(ToolUtils.getFiles(list, "uuid").toArray());
      result = AjaxResult.resultSuccess("删除成功", null);
    } catch (Exception e) {
      result = AjaxResult.resultFail("删除失败", null);
      logger.error(e.getMessage(), e);
    }
    return result;
  }

  /**
   * 查看
   * 
   * @author chenchuan 2014年11月9日
   */
  @MethodLog("查看商品信息")
  @RequestMapping("/viewMaterial")
  public String viewMaterial(HttpServletRequest request, Model model) {

    String uuid = request.getParameter("uuid");
    Material info = null;
    try {
      info = materialService.findByUuid(uuid);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    model.addAttribute("info", JSONUtil.obj2Json(info));
    model.addAttribute("status", Constants.VIEW);
    return "/base/MaterialEdit";
  }

  /**
   * 修改
   * 
   * @author chenchuan 2014年11月9日
   */
  @MethodLog("修改商品信息")
  @RequestMapping("/alterMaterial")
  public String alterMaterial(HttpServletRequest request, Model model) {
    String uuid = request.getParameter("uuid");
    Material info = null;
    try {
      info = materialService.findByUuid(uuid);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    model.addAttribute("info", JSONUtil.obj2Json(info));
    model.addAttribute("status", Constants.EDIT);
    return "/base/MaterialEdit";
  }

  /**
   * 添加
   * 
   * @author chenchuan 2014年11月9日
   */
  @MethodLog("新增商品信息")
  @RequestMapping("/addMaterial")
  public String addMaterial(HttpServletRequest request,Model model) {
    model.addAttribute("number",getBaseNumber(Material.BIZTYPE));
    model.addAttribute("matCategoryUuid",request.getParameter("matCategoryUuid"));
    return "/base/MaterialEdit";
  }

  /**
   * list列表数据加载
   * 
   * @author chenchuan 2014年11月9日
   */
  @MethodLog("查询商品信息")
  @RequestMapping("/listData")
  @ResponseBody
  public String ListData(HttpServletRequest request) {
    JSONObject data = null;
    // 获取条件
    // Map<String, Object> cond = JSONUtil.json2Map(request.getParameter("cond"));
    // 分页条件
    int page = Integer.parseInt(request.getParameter("page"));
    int pageSize = Integer.parseInt(request.getParameter("pagesize"));
    String sortname = request.getParameter("sortname");
    String sortorder = request.getParameter("sortorder");
    String isGroupM = request.getParameter("isGroupM");
    String rigidCondition = request.getParameter("rigidCondition");
    String where = request.getParameter("where");
    if(isGroupM != null && !"".equals(isGroupM)){
    	if(where != null && !"".equals(where)){
    		where = where + "and isGroupM = '"+isGroupM+"'";
    	}else{
    		where ="isGroupM = '"+isGroupM+"'";
    	}
    }
    //左边树的id
    if(!StringUtils.isEmpty(rigidCondition)){
      if(where != null && !"".equals(where)){
        where = where + " and "+rigidCondition+" ";
      }else{
          where = rigidCondition;
      }
    }
    // 分页器
    Pager pager = Pager.convert(page, pageSize, sortname, sortorder);
    try {
      pager = materialService.findByCondition(where, pager);
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("Rows", pager.getList());
      map.put("Total", pager.getCount());
      data = JSONObject.fromObject(map);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    return data.toString();
  }
  
  /**
   * list列表数据加载
   * 
   * @author chenchuan 2014年11月9日
   */
  @MethodLog("查询商品辅助计量单位")
  @RequestMapping("/listEntryData")
  @ResponseBody
  public String listEntryData(HttpServletRequest request) {
    JSONObject data = null;
    // 获取条件
    // Map<String, Object> cond = JSONUtil.json2Map(request.getParameter("cond"));
    // 分页条件
    int page = Integer.parseInt(request.getParameter("page"));
    int pageSize = Integer.parseInt(request.getParameter("pagesize"));
    String sortname = request.getParameter("sortname");
    String sortorder = request.getParameter("sortorder");
    String materialId = request.getParameter("materialId");
    String where = request.getParameter("where");
    where = "parentId = '"+ materialId+"'";
    // 分页器
    Pager pager = Pager.convert(page, pageSize, sortname, sortorder);
    try {
      pager = materialService.findByEntryCondition(where, pager);
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("Rows", pager.getList());
      map.put("Total", pager.getCount());
      data = JSONObject.fromObject(map);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    return data.toString();
  }
  
  @RequestMapping("/checkNumberUsed")
  public void checkNumberUsed(HttpServletRequest request, HttpServletResponse response) throws IOException{
    String uuid = request.getParameter("uuid");
    String number = request.getParameter("number");
    response.reset();
    response.setContentType("text/html;charset=UTF-8");
   //业务逻辑操作countByParams得到值并存储到num中
    SysUser sysuser = null;
    try {
      if(StringUtils.isEmpty(number)){
        response.getWriter().print(false);  
      }else{
        if(materialService.checkNumberUsed(uuid,number)){
          response.getWriter().print(false);  
        }else{
          response.getWriter().print(true);  
        }
      }
    } catch (Exception e) {
      response.getWriter().print(false);
      logger.error(e.getMessage(),e);
    }
  }
  
}
